package com.example.mapdata.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.mapdata.utils.JwtUtils;
import com.example.mapdata.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override // 目标资源方法前运行,返回true:执行 返回false:不执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("是否放行 执行Controller方法...");
        // 进行登录校验 判断是否携带Jwt
        String url = request.getRequestURI().toString();
        log.info("获取到的url: {}", url);
        // 登录接口放行
        if (url.contains("/login")) {
            log.info("登录接口放行...");
            return true;
        }
        log.info("非登录接口,进行登录校验...");
        String jwt = request.getHeader("token");
        // 判断是否携带token
        if (!StringUtils.hasLength(jwt)) {
            log.info("未携带token,禁止访问...");
            // Result error = Result.error("未携带token,禁止访问...");

            Result error = Result.error("未携带token,禁止访问...");
            String s = JSONObject.toJSONString(error);

            // 设置响应内容类型和字符编码
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(s);
            return false;
        }

        // 解析 jwt 是否失效
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            // jwt令牌解析失效
            e.printStackTrace();
            log.info("jwt令牌解析失效,禁止访问...");

            Result error = Result.error("jwt令牌解析失效,禁止访问...");
            String s = JSONObject.toJSONString(error);
            // 设置响应内容类型和字符编码
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(s);

            return false;
        }

        // jwt令牌解析成功
        log.info("jwt令牌解析成功,放行...");
        return true;
    }

    @Override // 目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle...");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override // 视图渲染完毕后运行,最后一步
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
